package top.sqdpt.file.strategy.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.sqdpt.file.entity.dto.FileUpload;
import top.sqdpt.file.enums.FileStorageType;
import top.sqdpt.file.strategy.FileStorageStrategy;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author pengtao
 * @date 2025/3/27
 * @Descciption
 **/
@Component
@Slf4j
public class LocalFileStorageStrategy implements FileStorageStrategy {

    private final static String localBaseFilePath = "/files/uploads";

    @Override
    public FileStorageType getFileStorageType() {
        return FileStorageType.LOCAL;
    }


    @Override
    public String saveFile(FileUpload fileUpload) throws IOException {
        String originalFilename = fileUpload.getFilename();
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = originalFilename.substring(dotIndex + 1);
        }
        String newFileName = UUID.randomUUID() + "." + extension;
        Path filePath = Paths.get(localBaseFilePath, newFileName);
        Files.createDirectories(filePath.getParent());
        // 保存文件
        try (InputStream inputStream = fileUpload.getInputStream(); OutputStream outputStream = Files.newOutputStream(filePath)) {
            inputStream.transferTo(outputStream);
        }
        return filePath.toString();
    }

    @Override
    public String saveFile(String text) throws IOException {
        String newFileName = UUID.randomUUID() + ".txt";
        Path filePath = Paths.get(localBaseFilePath, newFileName);
        Files.createDirectories(filePath.getParent());
        Files.writeString(filePath, text, StandardCharsets.UTF_8);
        return filePath.toString();
    }


}
